package org.yxj.videolibrary.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import org.yxj.videolibrary.R;
import org.yxj.videolibrary.i.BasePlayControl;
import org.yxj.videolibrary.i.ControlPlayListener;
import org.yxj.videolibrary.i.PlayVideoListener;


/**
 * 播放控制器
 *
 * @author yxj on 2022/9/9
 */
public class MediaPlayerControlView extends FrameLayout implements BasePlayControl, View.OnClickListener, View.OnLongClickListener {

    private View view;
    /**
     * 底部控制栏按钮
     */
    private PlayControlView playControlView;
    /**
     * 错误界面
     */
    private PlayErrorView playErrorView;
    /**
     * 加载动画view
     */
    private VideoLoadView mVideoLoadView;

    /**
     * 播放器的头view
     */
    private PlayHeadView playHeadView;

    /**
     * 中心播放按钮
     */
    private ImageView imPlay;
    /**
     * 功能控制按钮
     */
    private ControlPlayListener controlPlayListener;
    /**
     * 占位图
     */
    private ImageView imPlaceHolder;
    /**
     * 是否已经准备好
     */
    private boolean isPrepared = false;

    /**
     * 是否已经渲染
     */
    private boolean isSurfaceTextureAvailable;

    /**
     * 是否支持点击视频功能
     */
    private boolean isSupportOnClick;

    /**
     * 是否支持长按视频功能
     */
    private boolean isSupportOnLongClick;

    /**
     * 用户交互的回调事件
     */
    private PlayVideoListener playVideoListener;

    public MediaPlayerControlView(Context context) {
        this(context, null);
    }


    public MediaPlayerControlView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public MediaPlayerControlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addView(view = LayoutInflater.from(context).inflate(R.layout.control_layout, this, false));
        initView();
        initClick();
    }


    private void initClick() {
        view.setOnClickListener(this);
        view.setOnLongClickListener(this);
        imPlay.setOnClickListener(this);
        playErrorView.setOnClickListener(this);
        setOnClickListener(this);
    }


    private void initView() {
        imPlay = view.findViewById(R.id.imPlay);
        playControlView = view.findViewById(R.id.mPlayControlView);
        playErrorView = view.findViewById(R.id.playErrorView);
        mVideoLoadView = view.findViewById(R.id.mVideoLoadView);
        imPlaceHolder = view.findViewById(R.id.imPlaceHolder);
        playHeadView = view.findViewById(R.id.playHeadView);
    }


    /**
     * 音量是否开启
     */
    public void setVolumeClose(boolean volumeOpen) {
        playControlView.showVolumeIcon(volumeOpen);
    }


    /**
     * @param drawable
     * @param margin
     */
    public void setHeadCancelIcon(Drawable drawable, MarginLayoutParams margin) {
        playHeadView.setHeadCancelIcon(drawable, margin);
    }


    /**
     * 是否支持长按事件
     *
     * @param supportOnLongClick
     */
    public void setSupportOnLongClick(boolean supportOnLongClick) {
        isSupportOnLongClick = supportOnLongClick;
    }


    /**
     * 是否支持点击视频
     *
     * @param b
     */
    public void setSupportOnClick(boolean b) {
        isSupportOnClick = b;
    }


    /**
     * @param playVideoListener
     */
    public void setPlayVideoListener(PlayVideoListener playVideoListener) {
        this.playVideoListener = playVideoListener;
        playHeadView.setPlayVideoListener(playVideoListener);
    }

    /**
     * 设置默认加载动画
     *
     * @param mode
     */
    public void setDefaultLoad(VideoLoadView.LoadAnimMode mode) {
        mVideoLoadView.setDefaultLoading(mode);
    }

    /**
     * 设置默认加载动画
     *
     * @param drawable
     */
    public void setLoadAnim(Drawable drawable) {
        mVideoLoadView.setLoadDrawable(drawable);
    }


    /**
     * 是否支持播放头
     *
     * @param b
     */
    public void setSupportHeadView(boolean b) {
        playHeadView.setVisibility(b ? VISIBLE : GONE);
    }


    /**
     * 是否支持沉嵌式状态栏
     *
     * @param supportSubmergedBar
     */
    public void setSupportSubmergedBar(boolean supportSubmergedBar) {
        playHeadView.setSupportSubmergedBar(supportSubmergedBar);
    }


    /**
     * 添加扩展view
     */
    public void addHeadView(View view) {
        playHeadView.addHeadView(view);
    }


    /**
     * 是否支持控制
     *
     * @param supportControl
     */
    public void setSupportControl(boolean supportControl) {
        this.supportControl = supportControl;
        playControlView.setVisibility(supportControl ? VISIBLE : GONE);
    }


    /**
     * 是否支持控制条
     */
    private boolean supportControl;


    /**
     * 暂停icon资源图片
     */
    public void setPauseIcon(Drawable pauseIcon) {
        playControlView.setPauseIcon(pauseIcon);
    }

    /**
     * 播放icon資源图片
     */
    public void setPlayIcon(Drawable playIcon) {
        playControlView.setPlayIcon(playIcon);
    }


    /**
     * 中心播放按钮icon资源
     */
    public void setCenterPlayIcon(Drawable centerPlayIcon) {
        if (centerPlayIcon != null) {
            imPlay.setImageDrawable(centerPlayIcon);
        }
    }


    /**
     * 占位图
     *
     * @param placeHolder
     */
    @Override
    public void setPlaceHolder(String placeHolder) {
        if (!TextUtils.isEmpty(placeHolder)) {
            Glide.with(getContext().getApplicationContext())
                    .load(placeHolder)
                    .into(imPlaceHolder);
            imPlaceHolder.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imPlaceHolder
                    .animate()
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            imPlaceHolder.setVisibility(GONE);
                        }
                    })
                    .setDuration(100)
                    .alpha(0).start();
        }
    }


    /**
     * @param w
     * @param h
     */
    public void setPlaceHolderSize(int w, int h) {
        ViewGroup.LayoutParams p = imPlaceHolder.getLayoutParams();
        p.width = w;
        p.height = h;
        imPlaceHolder.setLayoutParams(p);
        imPlaceHolder.setVisibility(VISIBLE);
    }


    @Override
    public void isSurfaceTextureAvailable(boolean b) {
        isSurfaceTextureAvailable = b;
    }


    /**
     * 是否显示占位图
     *
     * @param b
     */
    public void showPlaceHolder(boolean b) {
        if (imPlaceHolder != null) {
            if (b){
                imPlaceHolder.setVisibility(VISIBLE);
            }else {
                imPlaceHolder
                        .animate()
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                imPlaceHolder.setVisibility(GONE);
                            }
                        })
                        .setDuration(500)
                        .alpha(0).start();
            }
        }
    }


    /**
     * 控制
     *
     * @param controlPlayListener
     */
    public void setControlPlayListener(ControlPlayListener controlPlayListener) {
        this.controlPlayListener = controlPlayListener;
        if (playControlView != null) {
            playControlView.setControlPlayListener(controlPlayListener);
        }
    }


    @Override
    public void init() {
        if (imPlay != null) {
            imPlay.setVisibility(VISIBLE);
        }
    }

    /**
     * 准备完成
     *
     * @param mediaPlayer
     */
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        if (imPlay != null) {
            imPlay.setVisibility(VISIBLE);
        }
        isPrepared = true;

        if (isLoading) {
            isLoading = false;
            if (controlPlayListener != null) {
                controlPlayListener.play();
            }
        }
    }


    /**
     * 开始播放
     */
    @Override
    public void onStart() {
        if (supportControl) {
            playControlView.setVisibility(VISIBLE);
        }

        playControlView.showPause();
        imPlay.setVisibility(GONE);
        playErrorView.setVisibility(GONE);

        showPlaceHolder(false);
    }


    /**
     * 播放暂停
     */
    @Override
    public void onPause() {
        playControlView.showPlay();
        imPlay.setVisibility(VISIBLE);
    }


    /**
     * 重置播放
     */
    @Override
    public void onResetPlay() {

    }


    /**
     * 播放进度
     *
     * @param total
     * @param progress
     */
    @Override
    public void onProgress(int total, int progress) {
        Log.v("[MediaPlayerControl]->", "total=" + total + ",progress=" + progress);
        if (playControlView != null) {
            playControlView.setData(total, progress);
        }
    }


    /**
     * 显示视频播放
     */
    public void showVideoLoading() {
        if (mVideoLoadView != null) {
            mVideoLoadView.setVisibility(VISIBLE);
            imPlay.setVisibility(GONE);
            isLoading = true;
        }
    }


    /**
     * 缓冲
     *
     * @param b
     */
    @Override
    public void onBuffering(boolean b) {
        if (mVideoLoadView != null) {
            mVideoLoadView.setVisibility(b ? VISIBLE : GONE);
        }
    }


    @Override
    public void onBufferingUpdate(int p) {
        if (playControlView != null) {
            playControlView.setSecondaryProgress(p);
        }
    }


    @Override
    public void onError(MediaPlayer mp, int what, int extra) {
        if (supportControl && playControlView != null) {
            playControlView.setVisibility(GONE);
        }
        showPlaceHolder(false);
        imPlay.setVisibility(GONE);
        if (playErrorView != null) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("视频无法播放！").append("\n");
            stringBuffer.append("错误码：");
            if (what != 0) {
                stringBuffer.append("what=" + what).append("\n");
            }
            if (extra != 0) {
                stringBuffer.append("extra=" + extra);
            }
            playErrorView.setData(stringBuffer.toString());
        }
    }


    /**
     * 播放完成
     */
    @Override
    public void onComplete() {
        playControlView.showPlay();
        imPlay.setVisibility(VISIBLE);
        showPlaceHolder(true);
    }


    /**
     * 停止播放
     */
    @Override
    public void onStop() {
    }


    /**
     * 是否正在加载中
     */
    private boolean isLoading;

    @Override
    public void onClick(View v) {
        if (!isPrepared) {
//            Toast.makeText(getContext(), "请稍等,视频准备中...", Toast.LENGTH_SHORT).show();
            showVideoLoading();
            return;
        }

        if (!isSurfaceTextureAvailable) {
            Toast.makeText(getContext(), "请稍等,视频渲染中...", Toast.LENGTH_SHORT).show();
            return;
        }

        int id = v.getId();
        if (id == R.id.imPlay) {
            if (controlPlayListener != null) {
                controlPlayListener.play();
            }
        } else if (id == R.id.playErrorView) {
            if (controlPlayListener != null) {
                controlPlayListener.play();
            }
        } else if (id == R.id.click_video) {
            if (playVideoListener != null) {
                if (isSupportOnClick) {
                    playVideoListener.onClickVideo();
                }
            }
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (playVideoListener != null) {
            if (isSupportOnLongClick) {
                playVideoListener.onLongClick();
            }
        }
        return false;
    }
}
